<?php
declare(strict_types=1);

namespace src\bootstrap;

use SplFileInfo;
use src\Application;
use src\ConfigRepository;

class LoadConfiguration
{
    public function bootstrap(Application $app)
    {
        $items = [];
        $app->instance('config', $config = new ConfigRepository($items));
        $this->loadConfigurationFiles($app, $config);
        date_default_timezone_set($config->get('app.timezone', 'UTC'));
    }

    protected function loadConfigurationFiles(Application $app, ConfigRepository $repository)
    {
        $files = $this->getConfigurationFiles($app);
        foreach ($files as $key => $path){
            $repository->set($key, require $path);
        }
    }

    protected function getConfigurationFiles(Application $app)
    {
        $configPath = realpath($app->configPath());
        if (!is_dir($configPath)){
            throw new \Exception('配置文件夹错误');
        }
        $files = [];
        $handle = opendir($configPath);
        while ($file = readdir($handle)){
            if (strpos($file, ".php")){
                $info = new SplFileInfo($configPath."/".$file);
                $files[$info->getBasename(".php")] = $info->getRealPath();
            }
        }
        return $files;
    }
}